﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using EEDS.Core;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace EEDS
{
    sealed class Util
    {
        private Util() { }

        public static Color[] ConvertIntArrayToColours(int[] colours)
        {
            Color[] retColours = new Color[colours.Length];

            for (int i = 0; i < retColours.Length; i++)
            {
                retColours[i] = Color.FromArgb(colours[i]);
            }

            return retColours;
        }

        public static T[,] RedimPreserve2D<T>(T[,] oldT, Size newSize)
        {
            T[,] newT = new T[newSize.Width, newSize.Height];

            for (int i = 0; i < newSize.Width; i++)
            {
                for (int j = 0; j < newSize.Height; j++)
                {
                    try
                    {
                        newT[i, j] = oldT[i, j];
                    } catch (ArgumentOutOfRangeException) { }
                }
            }

            return newT;
        }

        public static Bitmap ConvertImagePalette(Bitmap emblem, Palette palette)
        {
            Bitmap newEmblem = new Bitmap(32, 32, PixelFormat.Format4bppIndexed);

            for (int i = 0; i < newEmblem.Palette.Entries.Length; i++)
            {
                try
                {
                    newEmblem.Palette.Entries[i] = palette.Colours[i];
                }
                catch (ArgumentOutOfRangeException)
                {
                    newEmblem.Palette.Entries[i] = palette.BackColour;
                }
            }

            BitmapData data;
            byte[] pixels;

            data = newEmblem.LockBits(new Rectangle(0, 0, newEmblem.Width, newEmblem.Height), ImageLockMode.WriteOnly, newEmblem.PixelFormat);
            pixels = new byte[data.Stride * data.Height];
            Marshal.Copy(data.Scan0, pixels, 0, data.Stride * data.Height);

            for (int x = 0; x < newEmblem.Height; x++)
            {
                for (int y = 0; y < newEmblem.Width; y++)
                {
                    int index = y * newEmblem.Height + x;
                    byte pixel = (byte)palette.GetIndexOf(newEmblem.GetPixel(x, y));
                    if (index % 2 == 1)
                        pixels[index] |= pixel;
                    else
                        pixels[index] |= (byte)(pixel << 4);
                }
            }

            Marshal.Copy(pixels, 0, data.Scan0, data.Stride * data.Height);
            newEmblem.UnlockBits(data);

            return newEmblem;
        }
    }
}
